package com.wpp.data_structure.stack;

/**
 * @author wpp25
 * @date 2021/5/28 19:59
 * @description：
 */
public class DefaultStack<T>  implements MyStackParent<T>{
   //  栈底 {1,2,3} 栈顶
   private T[] arr;

   private int size;

    public DefaultStack(int capability) {
        if (capability < 0) {
            throw new IllegalArgumentException("capability less 0");
        }
        this.size = 0;
        arr = (T[]) new Object[capability];
    }

    public DefaultStack() {
        this(8);
    }

    @Override
    public void push(T t) {
        if (size >= arr.length >> 1) {
            expand();
        }
        arr[size++] = t;
    }

    @Override
    public T peek() {
        if (size <= 0) {
            return null;
        }

        return arr[size -1];
    }

    @Override
    public T pop() {
        if (size <= 0) {
            return null;
        }
        if (size <= arr.length >> 1) {
            shrink();
        }
        return arr[size-- -1];
    }

    public static void main(String[] args) {
        int size = 3;
        int[] arr = {1,2,3};
        System.out.println(arr[size-- - 1]);
        System.out.println(size);
    }

    @Override
    public String print() {
        StringBuilder sb = new StringBuilder("栈底：");
        for (int i = 0; i < size; i++) {
            sb.append(arr[i]);
            if (i < size - 1) {
                sb.append(",");
            }
        }
        sb.append("栈顶").append(" size: ").append(size).append(" length: ").append(arr.length);
        return sb.toString();
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean empty() {
        return size == 0;
    }

    private void expand(){
        T[] arrNew = (T[]) new Object[arr.length << 1];
        for (int i = 0; i < size; i++) {
            arrNew[i] = arr[i];
        }
        arr = arrNew;
    }

    private void shrink(){
        T[] arrNew = (T[]) new Object[arr.length >> 1];
        for (int i = 0; i < size; i++) {
            arrNew[i] = arr[i];
        }
        arr = arrNew;
    }
}
